<template>
  <NuxtLink
    v-if="to && !disabled"
    class="g-link g-link-router-link"
    :class="{'hover:underline': underline}"
    :to="to"
    :target="target"
  >
    <slot />
  </NuxtLink>
  <a
    v-else
    class="g-link g-link-a"
    :class="{'hover:underline': underline}"
    :href="disabled || !href ? defaultHref : href"
    :target="target"
    :disabled="disabled"
    :rel="nofollow"
    @click.prevent="onBeforeJump"
  >
    <slot />
  </a>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import type { IGLink } from './type'

const props = defineProps<IGLink>()
const attrs = useAttrs()
const defaultHref = ref('javascript:void(0)')

function onBeforeJump() {
  const origin = (import.meta as any).env.VITE_HOST
  if (!props.href)
    return false
  if (props.target && props.target.includes('blank')) {
    window.open(`${origin}${props.href}`)
    return false
  }
  window.location.href = `${origin}${props.href}`
  return false
}

const nofollow = computed(() => {
  if (attrs.ref)
    return attrs.rel
  if (!props.to && !props.href)
    return 'nofollow'
  if (props.href && /http/.test(props.href) && !/gitcode/.test(props.href))
    return 'nofollow'
  return undefined
})
</script>

<style lang="scss" scoped>
@import "devui-theme/styles-var/devui-var.scss";

.g-link {
  color: inherit;

  &:hover {
    color: var(--devui-link);
  }

  &[disabled="true"] {
    cursor: no-drop;
    color: $devui-disabled-text !important;

    &:hover,
    &:active {
      color: $devui-disabled-text !important;
    }
  }
}
</style>
